import miniApp, {
    analyticsBase,
    authorizeParams,
    gameRecorderStartParams,
    getUserInfoParams,
    loadParams,
    loginParams, ModalParams, SHARE_VIDEO_SORT_TYPE, ShareVideoRankDetail,
    toastParams
} from "../miniApp";
import {dataField} from "../dataField";
import {UMA_SDK} from "../../../../sdk/uma/src/umaConfig";

export interface WxRewardedVideoAdParam {
    // 属性	类型	默认值	必填	说明	最低版本
    adUnitId: string;		//是	广告单元 id
    multiton?: boolean;	//	否	是否启用多例模式，默认为false	2.8.0
}

export interface WxRewardedVideoAd {
    //加载激励视频广告。
    load: () => Promise<any>;
    //显示激励视频广告。激励视频广告将从屏幕下方推入。
    show: () => Promise<any>;
    //销毁激励视频广告实例。
    destroy: () => void;
    //监听激励视频广告加载事件。
    onLoad: (callback: () => void) => void;
    //取消监听激励视频广告加载事件
    offLoad: (callback: () => void) => void;
    //监听激励视频错误事件。
    onError: (callback: () => void) => void;
    //取消监听激励视频错误事件
    offError: (callback: () => void) => void;
    //监听用户点击 关闭广告 按钮的事件。
    onClose: (callback: (res: { isEnded: boolean }) => void) => void;
    //取消监听用户点击 关闭广告 按钮的事件
    offClose: (callback: () => void) => void;
}

const wx: any = window['wx'];
export default class WxApi extends miniApp {
    drawHead(headUrl: string): Promise<cc.SpriteFrame> {
        throw new Error("Method not implemented.");
    }
    fullScreenVideo(): Promise<void> {
        throw new Error("Method not implemented.");
    }
    LocalInBlockCityList(): boolean {
        return false;
    }

    vibrate(type): void {

    }
 
    protected m_appId: string = 'wx2edf2ac52464dcae';
    protected m_secret: string = '1c7ea66258fe921c8f8a2dd229756e5c';
    protected m_adUnitId: string = 'adunit-3f5c64c3e81acb30';

    //微信视频广告组件
    private m_rewardedVideoAd: WxRewardedVideoAd = null;

    getUserInfo(params: getUserInfoParams): void {
        wx.getUserInfo(params);
    }

    showToast(params: toastParams): void {
        wx.showToast(params);
    }

    showLoading(params: loadParams): void {
        wx.showLoading(params);
    }

    hideLoading(): void {
        wx.hideLoading()
    }

    preCreateUnits(): void {
        wx.showShareMenu({
            // withShareTicket: true,
        });
        this.createRewardedVideoAd({adUnitId: this.m_adUnitId});
        //
        console.log('wx 初始化友盟参数', typeof uma);
        uma.init({
            appKey: UMA_SDK.APP_KEY,
            useOpenid: false,// default true
            autoGetOpenid: true,
            debug: true,
            uploadUserInfo: true// 上传用户信息，上传后可以看到有用户头像和昵称的分享信息
        });
    }

    loadAndShowVideoAd(successCallback: () => void, errorCallback: (error: any) => void, completeCallback?: () => void): void {
        if (this.m_rewardedVideoAd == null) {
            console.error('微信广告视频组件不存在');
            errorCallback(null);
            return;
        }
        this.m_rewardedVideoAd.load().then(() => {
            this.m_rewardedVideoAd.show().then(() => {
                this.m_rewardedVideoAd.onClose((res) => {
                    if (res && res.isEnded) {
                        successCallback();
                    } else {
                        errorCallback('视频未播放完');
                    }
                    completeCallback && completeCallback();
                })
            }).catch(() => {
                /**
                 // 用户触发广告后，显示激励视频广告
                 videoAd.show().catch(() => {
                    // 失败重试
                    videoAd.load()
                        .then(() => videoAd.show())
                        .catch(err => {
                            console.log('激励视频 广告显示失败')
                        })
                })
                 */
                errorCallback('视频显示错误');
                completeCallback && completeCallback();
            })
        }).catch(() => {
            errorCallback('视频加载错误');
            completeCallback && completeCallback();
        });
    }

    login(params: loginParams): void {
        wx.login(params);
    }

    authorize(params: authorizeParams): void {
        params.scope = params.scope || 'scope.userInfo';
        wx.authorize(params);
    }

    validAppId(): void {
        if (wx.getAccountInfoSync().miniProgram.appId != this.m_appId) {
            console.error('非法盗用游戏资源将受到法律制裁');
            cc.game.end();
            throw '非法盗用游戏资源将受到法律制裁';
        }
    }

    isHaveShareVideo(): boolean {
        return false;
    }

    gameRecordStart(params: gameRecorderStartParams, onStart?: (res: any) => void): void {
        if (!this.isHaveShareVideo()) return;
        throw new Error("#112 微信录屏功能.");
    }

    gameRecordStop(): boolean {
        if (!this.isHaveShareVideo()) return false;
        return true;
    }

    shareGameRecordVideo(successCb?: () => void, failCb?: () => void): void {
        if (!this.isHaveShareVideo()) return;
        throw new Error("#120 微信分享录屏功能.");
    }

    isProduction(): boolean {
        return true;
    }

    reportAnalytics(eventKey: string, data: any): void {
        console.log('wx 发送埋点', eventKey, data);
        // wx.reportMonitor(eventKey, data);
        console.log('wx 上报友盟事件 trackEvent', eventKey, data);
        uma.trackEvent(eventKey, data);
    }

    clearMemory(): void {
        wx.triggerGC();
    }

    shareAppMessage(args: any) {
        let title = '';
        if (args) {
            title = args.title;
        }
        wx.shareAppMessage({
            title,
        })
    }

    protected createRewardedVideoAd(param: WxRewardedVideoAdParam): void {
        this.m_rewardedVideoAd = wx.createRewardedVideoAd(param);
    }

    PlayLastRecordSound(scale?: number, successCb?: () => void, errorCb?: () => void): void {
    }

    StartRecordSound(): void {
    }

    StopRecordSound(successCallback?: () => void): void {
    }

    addShortcut(): Promise<boolean> {
        return Promise.resolve(false);
    }

    createMoreGameBtn(): void {
    }

    drawUrlImage(url: string, overCb: (spf: cc.SpriteFrame) => void): void {
        let image = wx.createImage();
        image.onload = function () {
            let texture = new cc.Texture2D();
            texture.initWithElement(image);
            texture.handleLoadedTexture();
            overCb(new cc.SpriteFrame(texture));
        };
        image.src = url;
    }

    getShareVideoRank(sortType: SHARE_VIDEO_SORT_TYPE, successCb: (data: ShareVideoRankDetail[]) => void): void {
    }

    hideBanner(): void {
    }

    operateGameLive(): void {
    }

    reportAdClickNativeAd(): void {
    }

    showAddFavoriteGuide(successCallback?: () => void, failCallback?: () => void, completeCallback?: () => void): void {
    }

    showBannerAD(node: cc.Node, successCallback?: () => void, errorCallback?: (error: any) => void, onCloseCallBack?: () => void, setBannerPosition?: ({screenWidth, screenHeight}: { screenWidth: any; screenHeight: any }) => cc.Vec2): void {
    }

    showInterstitialAd(onAdClose: () => void, onFailed: () => void): void {
    }

    showNativeAd(successCallback: (a: Array<any>) => void, errorCallback: (error: any) => void, completeCallback?: () => void): void {
    }

    showVideo(videoUrl: string): void {
    }

    subscribeMessage(successCallback?: () => void, failCallback?: () => void, completeCallback?: () => void): void {
    }

    showModal(params: ModalParams): void {
    }

    async commitRank(rankId: dataField.RANK_ID, score: number): Promise<boolean> {
        return Promise.resolve(false);
    }

    async showRank(rankId: dataField.RANK_ID): Promise<boolean> {
        return Promise.resolve(false);
    }

    //
    navigateToMiniGame(appId: string, successCallback?: () => void, failCallback?: () => void): void {
        //
        wx.navigateToMiniProgram({
            appId: appId,
            success: (res) => {
                successCallback && successCallback();
            },
            fail: (res) => {
                failCallback && failCallback();
            }
        });
    }
}

























